<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import { TypeBalanceApply } from '@src/interfaces/TypeBalanceApply.ts'
import { storeToRefs } from 'pinia'
import useUserStore from '@src/stores/useUserStore.ts'
import TokenUtil from '@util/TokenUtil.ts'
import { Picture as IconPicture } from '@element-plus/icons-vue'
import { router } from '@util/RouterUtil.ts'
import { applyBalanceApi } from '@src/apis/balanceApply.ts'
import { getImageUrlByImageName, uploadImageApi } from '@src/apis/imageApi.ts'
const userInfo = storeToRefs(useUserStore()).userInfo
const formRef = ref<FormInstance>()
const formData = ref<TypeBalanceApply>({
  amount: 1,
  classId: 0,
  reason: '',
  receiveImageName: '',
  userId: 0,
})
onMounted(async () => {
  await TokenUtil.refresh()
  formData.value.userId = <number>userInfo.value.id
  formData.value.classId = <number>userInfo.value.classId
})
const formRules = ref<FormRules<typeof formData>>({
  reason: [
    {
      required: true,
      message: '请输入申请理由',
      trigger: 'blur',
    },
  ],
  amount: [
    {
      required: true,
      message: '请输入申请金额',
      trigger: 'blur',
    },
    {
      validator: (_, value, callback) => {
        if (typeof value === 'string') {
          try {
            value = parseFloat(value)
          } catch (e) {
            callback(new Error('金额必须为数字'))
            return
          }
        }
        if (isNaN(value)) {
          callback(new Error('金额必须为数字'))
          return
        }
        if (value <= 0) {
          callback(new Error('金额必须大于0'))
          return
        }
        callback()
      },
      trigger: 'blur',
    },
  ],
  receiveImageName: [
    {
      required: true,
      message: '请上传收款二维码图片',
      trigger: 'blur',
    },
  ],
})

const uploadImage = ({ raw: file }: { raw: File }) => {
  uploadImageApi(file).then(({ data }) => {
    formData.value.receiveImageName = data
  })
}

const submitForm = () => {
  formRef.value?.validate((valid) => {
    if (!valid) return
    applyBalanceApi(formData.value).then(({ message }) => {
      ElMessage.success(message)
      toRecord()
    })
  })
}

const toRecord = () => {
  router.push('/balance-apply/record')
}

onMounted(async () => {
  await TokenUtil.refresh()
  if (!userInfo.value.classId) {
    ElMessage.warning('您还没有加入班级，请先加入班级')
    router.push('/class/join')
    return
  }
})
</script>

<template>
  <div>
    <h2><el-text>申请班费</el-text></h2>
    <el-dialog
      :model-value="true"
      title="申请班费"
      width="500"
      @closed="toRecord"
    >
      <el-form :model="formData" :rules="formRules" ref="formRef">
        <el-form-item prop="amount" label="申请金额">
          <el-input v-model="formData.amount" placeholder="请输入申请金额" />
        </el-form-item>
        <el-form-item prop="reason" label="申请理由">
          <el-input
            type="textarea"
            v-model="formData.reason"
            placeholder="请输入申请理由"
          />
        </el-form-item>
        <el-form-item prop="receiveImageName">
          <div class="upload-box">
            <el-upload
              :auto-upload="false"
              :on-change="uploadImage"
              :show-file-list="false"
              drag
            >
              <el-tooltip content="点击上传收款二维码">
                <el-image
                  :src="getImageUrlByImageName(formData.receiveImageName)"
                  :alt="formData.receiveImageName"
                >
                  <template #error>
                    <div class="image-slot">
                      <el-icon><icon-picture /></el-icon>
                    </div>
                  </template>
                </el-image>
              </el-tooltip>
            </el-upload>
          </div>
        </el-form-item>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </el-form>
    </el-dialog>
  </div>
</template>

<style scoped lang="less">
h2 {
  text-align: center;
  .el-text {
    font-size: 2em;
  }
}

.el-form {
  .upload-box {
    display: flex;
    justify-content: center;
    width: 100%;

    .image-slot {
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 30px;
      height: 300px;
      width: 450px;
    }
  }
}
.el-button {
  width: 100%;
}
</style>
